<template>
  <div class="make-course-outline">
    <div class="btns">
      <div class="ai-btn" @click="openAiGenerate()" v-if="!isPreview">
        <span>
          <img src="@/assets/img/ai-gif.gif" alt="AI 图标" />
          AI助手
        </span>
      </div>
      <el-upload
        v-if="!isPreview"
        ref="uploadRef"
        v-model:file-list="fileList"
        name="file"
        class="btn"
        action="/tes/file/word2markdown"
        :limit="1"
        :before-upload="beforeUpload"
        :on-success="handleSuccess"
        :on-error="handleError"
        :show-file-list="false"
      >
        <el-button class="btn">Word上传</el-button>
      </el-upload>
      <el-button class="btn" @click="saveAndPreview()" v-if="!isPreview"
        >保存并预览</el-button
      >
      <el-button
        class="btn"
        @click="returnEdit()"
        v-if="isPreview && markdownContent"
        >返回编辑</el-button
      >
    </div>
    <!-- markdown 内容-编辑 -->
    <div class="markdown-content" v-if="!isPreview">
      <MdEditor
        class="mdEditor_edit"
        ref="mdEditor"
        v-model="markdownContent"
        :toolbars="toolbars"
        :footers="[]"
        :preview="false"
        @onHtmlChanged="onHtmlChanged"
      />
    </div>
    <!-- 预览效果 -->
    <div class="markdown-content" v-if="isPreview && markdownContent">
      <MdEditor
        class="mdEditor"
        v-model="markdownHTML"
        :toolbars="[]"
        :footers="[]"
        :preview="true"
        :editing="false"
        :show-toolbar="false"
        :show-footer="false"
      />
    </div>
  </div>

  <!-- AI生成弹窗 -->
  <el-dialog
    class="ai-generate-course-outline"
    v-model="showAiGenerate"
    width="60%"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-form :model="form" label-width="auto">
      <!-- <el-form-item label="章节名称：">
        <el-cascader
          v-model="form.chapterName"
          :options="chapterNameList"
          :props="cascaderProps"
          placeholder="请选择章节"
          class="chapter-section-select"
          clearable
        />
      </el-form-item> -->
      <el-form-item label="知识点：">
        <el-input
          v-model="form.knowledgePoints"
          type="textarea"
          :rows="15"
          placeholder="请输入章节及知识点内容"
          class="knowledge-points-textarea"
        />
      </el-form-item>
      <el-form-item label="课时数：">
        <el-input-number v-model="form.courseTimeNum" :min="1" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button color="#155EEF" @click="generateOutline()"> 保存 </el-button>
        <el-button @click="showAiGenerate = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      courseId: "",
      loading: null,
      fileList: [],
      chapterNameList: [],
      treeData: [],
      markdownContent: "",
      markdownHTML: "",
      isPreview: false,
      showAiGenerate: false,
      form: {
        chapterName: [],
        courseTimeNum: 1,
        knowledgePoints: "",
      },
      toolbars: [
        "bold",
        "underline",
        "italic",
        "strikeThrough",
        "sub",
        "sup",
        "quote",
        "unorderedList",
        "orderedList",
        "task",
        "codeRow",
        "code",
        "link",
        "image",
        "table",
        "mermaid",
        "katex",
        "revoke",
        "next",
        "preview",
      ],
      isSending: false,
      isFirst: true,
      eventSource: null,
      loadingAI: null,
    };
  },
  created() {
    this.courseId = JSON.parse(localStorage.getItem("courseId"));
    this.getMarkdownContent();
    this.getTreeData();
  },
  methods: {
    // md转html
    onHtmlChanged(html) {
      this.markdownHTML = html;
    },

    // 获取markdown内容
    getMarkdownContent() {
      this.$axios
        .get(`/tes/course/${this.courseId}/resource?resourceType=15`)
        .then((res) => {
          this.markdownContent =
            res.data.courseOutline.creativeVersion[0]?.content;
          this.markdownHTML =
            res.data.courseOutline.displayVersion[0]?.htmlContent;

          // 如果有内容，默认显示预览模式
          if (this.markdownContent) {
            this.isPreview = true;
          }
        });
    },
    beforeUpload(file) {
      if (!file.name.endsWith(".doc") && !file.name.endsWith(".docx")) {
        this.$message.error("文件格式不正确，请上传.doc或.docx文件");
        return false;
      }
      this.loading = this.$loading({
        lock: true,
        text: "上传中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      return true;
    },
    handleSuccess(res, file, fileList) {
      if (res.code == 200) {
        this.markdownContent = res.data;
      } else {
        this.$message.error(res.message);
      }
      this.loading.close();
      this.$refs.uploadRef.clearFiles();
    },
    handleError(error, file, fileList) {
      console.log(error, file, fileList);
    },

    // 获取知识点树
    getTreeData() {
      this.$axios
        .get(`/tes/course/auto/make/chapter-kb?courseId=${this.courseId}`)
        .then((res) => {
          this.treeData = res.data;
          this.chapterNameList = res.data;
          // 将树形数据转换为文本格式
          this.form.knowledgePoints = this.convertTreeToText(res.data);
        });
    },

    // 将树形数据转换为文本格式
    convertTreeToText(treeData, depth = 0) {
      let result = "";
      treeData.forEach((node, index) => {
        // 根据层级添加缩进
        const indent = "  ".repeat(depth);
        result += `${indent}${node.label}\n`;

        // 如果有子节点，递归处理
        if (node.children && node.children.length > 0) {
          result += this.convertTreeToText(node.children, depth + 1);
        }
      });
      return result;
    },

    // 保存并预览
    saveAndPreview() {
      // 将markdown转换为HTML
      // const html = marked(this.markdownContent);
      if (!this.markdownContent) {
        this.$message.warning("请先输入内容");
        return;
      }
      const queryObj = {
        name: "课程大纲",
        content: this.markdownContent,
        htmlContent: this.markdownHTML,
      };
      const loading = this.$loading({
        lock: true,
        text: "保存中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.$axios
        .post(`/tes/course/${this.courseId}/resource?resourceType=15`, queryObj)
        .then((res) => {
          this.$message.success("保存成功");
          this.getMarkdownContent();
          this.isPreview = true;
        })
        .finally(() => {
          loading.close();
        });
    },

    handleClose() {
      this.showAiGenerate = false;
      this.form.chapterName = [];
      this.form.courseTimeNum = 1;
      // 重新获取并设置知识点内容
      if (this.treeData && this.treeData.length > 0) {
        this.form.knowledgePoints = this.convertTreeToText(this.treeData);
      }
    },

    openAiGenerate() {
      this.handleClose();
      this.showAiGenerate = true;
    },

    // 生成大纲
    generateOutline() {
      if (this.isSending) {
        this.$message.error("请等待回答结束");
        return;
      }

      // 检查知识点内容是否为空
      if (!this.form.knowledgePoints.trim()) {
        this.$message.error("请输入知识点内容");
        return;
      }

      this.loadingAI = this.$loading({
        lock: true,
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.showAiGenerate = false;
      //清空旧消息
      this.markdownContent = "";
      //立即锁定按钮
      this.isSending = true;
      // 只有当eventSource不存在时才创建新的EventSource连接
      if (!this.eventSource) {
        // 创建新的EventSource连接
        this.eventSource = new EventSource("/tes/graph/sse/connect");

        // 设置消息接收的回调函数
        this.eventSource.onmessage = (event) => {
          let data = event.data;
          if (data === "↖Start↘") {
            this.loadingAI.close();
          }
          if (data === "↖Done↘") {
            this.closeSend();
            return;
          }
          if (data.includes("↖Error↘")) {
            data = data.replaceAll("↖Error↘", "");
            this.$message.error(data);
            this.closeSend();
            this.loadingAI.close();
            return;
          }
          if (this.isFirst) {
            //首次接收的是id，不添加
            this.sendContent(data);
            this.isFirst = false;
          } else {
            data = data.replaceAll("↖Start↘", "");
            data = data.replaceAll("↖emsp↘", " ");
            data = data.replaceAll("↖br↘", "\n");
            data = data.replaceAll("↖tab↘", "   ");
            this.markdownContent += data;
          }
        };

        // 可选：监听错误事件，以便在出现问题时能够重新连接或处理错误
        this.eventSource.onerror = (event) => {
          console.log(event, "error");
          // 关闭出错的连接
          this.eventSource.close();
          // 重置eventSource变量，允许重建连接
          this.eventSource = null;
          // 解锁按钮
          this.isSending = false;
        };
      }
    },
    sendContent(id) {
      const data = {
        chapterName: this.form.knowledgePoints.trim(),
        connectId: id,
        courseName: localStorage.getItem("courseName"),
        theoreticalClassHours: this.form.courseTimeNum,
      };
      this.$axios
        .post("/tes/ai-assistant/send/1", data)
        .then((res) => {})
        .finally(() => {
          this.isSending = false;
          this.loadingAI.close();
        });
    },

    closeSend() {
      this.isSending = false;
      this.loadingAI.close();
      this.eventSource.close();
      this.eventSource = null;
    },

    returnEdit() {
      this.isPreview = false;
      // 确保编辑区域可见
      this.$nextTick(() => {
        // 如果有编辑器引用，可以聚焦到编辑器
        if (this.$refs.mdEditor) {
          this.$refs.mdEditor.focus();
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.make-course-outline {
  background-color: #fff;
  padding: 40px 30px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  min-height: 650px;
  .btns {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 10px;
    .ai-btn {
      display: flex;
      align-items: center;
      gap: 10px;
      span {
        position: relative;
        width: 85px;
        height: 25px;
        border-radius: 16px;
        background-color: #5297fb;
        font-size: 14px;
        color: #fff;
        text-align: right;
        line-height: 25px;
        padding-right: 15px;
        box-sizing: border-box;
        cursor: pointer;
        img {
          position: absolute;
          left: -15px;
          top: 50%;
          transform: translateY(-50%);
          width: 40px;
          height: 45px;
        }
        &:hover {
          img {
            transform: translateY(-50%) rotate(360deg);
            transition: all 0.5s;
          }
        }
      }
    }
    .btn {
      width: 100px;
      height: 32px;
      background: #457aff;
      border-radius: 4px;
      font-size: 14px;
      color: #ffffff;
      &:hover {
        background: #2e64e2;
      }
    }
  }
  .markdown-content {
    width: 100%;
    height: 100%;
    margin-top: 20px;

    // 预览
    .mdEditor {
      :deep(.md-editor-input-wrapper) {
        width: 0 !important;
      }
      :deep(.md-editor-resize-operate) {
        width: 0;
      }
      :deep(.md-editor-preview-wrapper::-webkit-scrollbar) {
        display: none;
      }
    }

    // 编辑
    // .mdEditor_edit {
    //   :deep(.md-editor-input-wrapper) {
    //     --md-scrollbar-thumb-color: #fff;
    //     --md-scrollbar-thumb-hover-color: #fff;
    //     --md-scrollbar-bg-color: #fff;
    //   }
    // }
  }

  .editormd-preview-container {
    padding: 0 40px 40px;
    text-align: left;
    font-size: 14px;
    line-height: 1.6;
    overflow-x: hidden;
    width: 100%;
    background-color: #fff;
    box-sizing: border-box;
  }

  .markdown-body {
    color: #333;
    /* overflow: hidden; */
    font-family: "Microsoft YaHei", Helvetica, "Meiryo UI", "Malgun Gothic",
      "Segoe UI", "Trebuchet MS", "Monaco", monospace, Tahoma, STXihei,
      "华文细黑", STHeiti, "Helvetica Neue", "Droid Sans", "wenquanyi micro hei",
      FreeSans, Arimo, Arial, SimSun, "宋体", Heiti, "黑体", sans-serif;
    font-size: 16px !important;
    line-height: 1.6;
    word-wrap: break-word;
    width: 100%;
  }
}
</style>

<!-- 弹窗样式 -->
<style lang="scss">
.ai-generate-course-outline {
  .el-dialog {
    height: 680px !important;
  }

  .el-dialog__body {
    padding: 25px !important;
  }

  .el-textarea__inner {
    height: 323px !important;
    min-height: 323px !important;
  }

  .knowledge-points-textarea {
    .el-textarea__inner {
      height: 400px !important;
      min-height: 400px !important;
      font-family: "Courier New", monospace;
      line-height: 1.6;
      padding: 15px;
      border-radius: 4px;
      resize: vertical;

      &::-webkit-scrollbar {
        display: none;
      }
      &::-webkit-scrollbar-thumb {
        background-color: #fff;
        border-radius: 3px;
      }
      &::-webkit-scrollbar-track {
        background-color: #fff;
      }
    }
  }
}
</style>
